<?php
namespace app\models;
use ac\component\tool\Tool;
use app\models\Basic;

use Yii;

class Tags extends Basic
{
    public $variable_name_repeat;
    
    public static function tableName()
    {
        return '{{%tags}}';
    }

    public function rules()
    {
        return [
            ['tag_name', 'required', 'message' => 'tag_name不能为空', 'on' => 'add'],
            ['tag_name', 'string', 'message' => 'tag_name必须是字符串',
                                'min' => 2, 'tooShort' => 'tag_name最短2位',
                                'max' => 16, 'tooLong' => 'tag_name最长16位'],
            ['tag_name', 'validateTagnameRepeat', 'on' => 'add'],
            ['heat', 'integer', 'message' => 'heat必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'heat最小存储0', 
                     'max'=>65535, 'tooBig' => 'heat最大存储65535'],
        ];
    }

    /*rules 标签名是否存在*/
    public function validateTagnameRepeat()
    {
        if(!$this->hasErrors()){
            $data = self::find()
                    ->where('tag_name = :name', [':name' => $this->tag_name])
                    ->one();
            if(!is_null($data)){
                $this->addError('repeatTagname', '该标签名已经存在');
            }
        }
    }


    /*
    添加
    $plus   是否需要把热度+1（如果存在的话）
    */
    public function addTag($data, $plus = false)
    {
        $this->scenario = 'add';
        // P($data);
        /*查看此标签名称是否存在 存在的话 热度+1*/
        $tag = self::find()->where('tag_name = :name', [':name' => $data['Tags']['tag_name']])->one();
        if(!is_null($tag)){
            if($plus){
                $tag->heat = $tag->heat+1;
                $tag->save(false);
            }
            return $tag->tid;
        }

        if($this->load($data) and $this->validate()){
            // P($this);
            if($this->save(false)){
                $tid = $this->getPrimaryKey();
                return $tid;
            }
        }
        return false;
    }

    /*
    修改
    $data       修改的数据 
    */
    public function modifyTag($data, $id)
    {
        // P($data);
        $tag = self::find()->where('tid = :id', [':id' => $id])->one();
        // P($tag);
        if(!is_null($tag)){
            if($this->load($data) and $this->validate()){
                if(isset($this->tag_name)){
                    $tag->tag_name = $this->tag_name;
                }
                // P($tag);
                if($tag->save(false)){
                    return true;
                }
            }
        };
        return false;
    }

    
}